package com.sys.object.common.upload;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.StringUtils;

import com.sys.object.common.context.Config;

/**
 * Servlet implementation class Uploadify
 */
public class UploadifyImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadifyImage() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String foldertype = request.getParameter("type");
		String savePath = Config.getConfigValue("loadpath").trim();
		String saveUrl = Config.getConfigValue("saveurl").trim();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());

		if (StringUtils.hasText(foldertype)) {
			savePath += foldertype + "/" + ymd + "/";
			saveUrl += foldertype + "/" + ymd + "/";
		} else {
			savePath += "image/" + ymd + "/";
			saveUrl += "image/" + ymd + "/";
		}

		File f1 = new File(savePath);
		if (!f1.exists()) {
			f1.mkdirs();
		}
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String extName = "";

		StringBuilder buf = new StringBuilder();
		int count = 0;
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				count++;
				name = item.getName();
				long size = item.getSize();
				String type = item.getContentType();

				if (name == null || name.trim().equals("")) {
					continue;
				}
				// 扩展名格式：
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				buf.append(name.substring(0, name.indexOf("."))).append("|");
				buf.append(size).append("|");
				File file = null;
				do {
					// 生成文件名：
					name = UUID.randomUUID().toString();
					file = new File(savePath + name + extName);
					buf.append(saveUrl + name + extName);
				} while (file.exists());
				File saveFile = new File(savePath + name + extName);

				try {
					item.write(saveFile);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		response.getWriter().print(buf.toString());
	}

}
